package discovery

import (
	"encoding/json"
	"fmt"
	"strings"
)

const (
	KeyDelimiter = ":"
)

type Server struct {
	Name      string `json:"name"`
	Addr      string `json:"addr"`
	Weight    int    `json:"weight"`
	Version   string `json:"version"`
	KeepALive int64  `json:"keepALive"`
}

// BuildGrantKey 构建租约 Key
func (server *Server) BuildGrantKey() string {
	return fmt.Sprintf("%s%s%s%s%s", server.Name, KeyDelimiter, server.Addr, KeyDelimiter, server.Version)
}

// ParseKey 将 key 字符串解析成对象
func ParseKey(key string) (*Server, error) {
	delimiter := strings.Split(key, KeyDelimiter)
	return &Server{
		Name:    delimiter[0],
		Addr:    delimiter[1],
		Version: delimiter[2],
	}, nil

}

// ParseValue 解析数据
func ParseValue(v []byte) (*Server, error) {
	s := new(Server)
	if err := json.Unmarshal(v, s); err != nil {
		return nil, err
	}
	return s, nil
}
